package com.eco.fanliapp.job.footprintjob;

import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.dao.SyUserFootprintMapper;
import com.eco.fanliapp.entity.SyUserFootprint;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateFormatUtils;
import com.eco.fanliapp.utils.DateUtils;
import com.eco.fanliapp.vo.respone.ResponeResults;
import org.quartz.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import javax.annotation.Resource;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @date 2019-11-18
 */
@DisallowConcurrentExecution
@PersistJobDataAfterExecution
public class FootprintTask implements Job, Serializable {


    private static final Logger log = LoggerFactory.getLogger(com.eco.fanliapp.job.footprintjob.FootprintTask.class);
    @Autowired
    private ITaoBaoService iTaoBaoService;

    @Autowired
    private SyUserFootprintMapper syUserFootprintMapper;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    public FootprintTask() {
    }

    @Override
    public void execute(JobExecutionContext context) {

        //取得job详情
        JobDetail jobDetail = context.getJobDetail();

        JobDataMap dataMap = jobDetail.getJobDataMap();

        int executeCount = 0;
        if (dataMap.containsKey("runCount")) {
            executeCount = dataMap.getInt("runCount");
        }

        // 增量计数并将其存储回 JobDataMap，这样可以适当保持工作状态
        executeCount++;
        dataMap.put("runCount", executeCount);

        long startTime = System.currentTimeMillis();
        log.info("***************************************开始执行足迹：executeCount=" + executeCount + "--startTime=" + startTime);
        //两小时之前分钟
        Date date = DateUtils.updateHourByDate(new Date() , -2);
        //两小时之前的分钟数-1
        Date dateBefore = DateUtils.updateMinByDate(date, -1);
        //格式两小时之前的分钟数-1
        String timeTwoHoursBefore = DateFormatUtils.getNowDateMin(dateBefore);

        //从缓存取出key  如果有值执行下一分钟插入  没有值 执行当前时间前一分钟 并放入缓存
        Map<String, Set<Long>> mapBefore = (Map<String, Set<Long>>) redisTemplate.opsForValue().get("footprintToDo_"+timeTwoHoursBefore);
        List<SyUserFootprint> footprintListBefore = new ArrayList<>();
        if (mapBefore != null && mapBefore.size() > 0) {
            for (String userID : mapBefore.keySet()
            ) {
                Long userId = Long.valueOf(userID);
                Set<Long> set = mapBefore.get(userId.toString());
                for (Long goodsId : set
                ) {
                    //判断今天是否插入
                    SyUserFootprint footprint = syUserFootprintMapper.selectFootPrintById(userId, goodsId);
                    if(footprint != null){
                        continue;
                    }else {
                        //根据商品id查询商品，获得商品信息
                        ServerResponse<ResponeResults> response = iTaoBaoService.getHdkSearchItemIdDetail(goodsId.toString(), userId, null, "0", 0,null);
                        if (response.getStatus() == 200 && response.getData() != null) {
                            List<ResponeResults.DataBean> dataBeans = response.getData().getData();
                            if (dataBeans != null && dataBeans.size() == 1) {
                                for (ResponeResults.DataBean bean : dataBeans
                                ) {
                                    SyUserFootprint syUserFootprint = new SyUserFootprint();
                                    syUserFootprint.setGoodsId(goodsId);
                                    syUserFootprint.setUserId(userId);
                                    syUserFootprint.setGoodsName(bean.getItemShortTitle());
                                    if (bean.getItemShortTitle().isEmpty() || bean.getItemShortTitle().equals("")) {
                                        syUserFootprint.setGoodsName(bean.getItemTitle());
                                    }
                                    syUserFootprint.setGoodsPicture(bean.getItempictUrl());
                                    syUserFootprint.setGoodsCoupon(new BigDecimal(bean.getCouponMoney()));
                                    syUserFootprint.setGoodsPrice(new BigDecimal(bean.getItemPrice()));
                                    syUserFootprint.setGoodsSubsidies(bean.getFanliMoney());
                                    syUserFootprint.setGoodsTkPrice(bean.getTheirPriceMoney());
                                    syUserFootprint.setBelongDate(new Date());
                                    if (bean.getItemType().equalsIgnoreCase("B")) {
                                        //2天猫
                                        syUserFootprint.setGoodsShopType(2);
                                    } else {
                                        //1淘宝
                                        syUserFootprint.setGoodsShopType(1);
                                    }
                                    syUserFootprint.setEnable(1);
                                    syUserFootprint.setDeleted(0);
                                    footprintListBefore.add(syUserFootprint);
                                }
                            }
                        }
                    }
                }
            }
        }
        //当前时间-1分钟
        Date minByDate = DateUtils.updateMinByDate(new Date(), -1);
        //格式化现在分钟数-1
        String timeNow = DateFormatUtils.getNowDateMin(minByDate);
        //足迹
        Map<String, Set<Long>> map = (Map<String, Set<Long>>) redisTemplate.opsForValue().get("footprintToDo_"+timeNow);
        List<SyUserFootprint> footprintList = new ArrayList<>();
        if (map != null && map.size() > 0) {
            for (String userID : map.keySet()
            ) {
                Long userId = Long.valueOf(userID);
                Set<Long> set = map.get(userId.toString());
                for (Long goodsId : set
                ) {
                    //判断今天是否插入
                     SyUserFootprint footprint = syUserFootprintMapper.selectFootPrintById(userId, goodsId);
                     if(footprint != null){
                         continue;
                     }else {
                         //根据商品id查询商品，获得商品信息
                         ServerResponse<ResponeResults> response = iTaoBaoService.getHdkSearchItemIdDetail(goodsId.toString(), userId, null,"0",0,null);
                         if (response.getStatus() == 200 && response.getData() != null) {
                             List<ResponeResults.DataBean> dataBeans = response.getData().getData();
                             if (dataBeans != null && dataBeans.size() == 1) {
                                 for (ResponeResults.DataBean bean : dataBeans
                                 ) {
                                     SyUserFootprint syUserFootprint = new SyUserFootprint();
                                     syUserFootprint.setGoodsId(goodsId);
                                     syUserFootprint.setUserId(userId);
                                     syUserFootprint.setGoodsName(bean.getItemShortTitle());
                                     if (bean.getItemShortTitle().isEmpty() || bean.getItemShortTitle().equals("")) {
                                         syUserFootprint.setGoodsName(bean.getItemTitle());
                                     }
                                     syUserFootprint.setGoodsPicture(bean.getItempictUrl());
                                     syUserFootprint.setGoodsCoupon(new BigDecimal(bean.getCouponMoney()));
                                     syUserFootprint.setGoodsPrice(new BigDecimal(bean.getItemPrice()));
                                     syUserFootprint.setGoodsSubsidies(bean.getFanliMoney());
                                     syUserFootprint.setGoodsTkPrice(bean.getTheirPriceMoney());
                                     syUserFootprint.setBelongDate(new Date());
                                     if (bean.getItemType().equalsIgnoreCase("B")) {
                                         //2天猫
                                         syUserFootprint.setGoodsShopType(2);
                                     } else {
                                         //1淘宝
                                         syUserFootprint.setGoodsShopType(1);
                                     }
                                     syUserFootprint.setEnable(1);
                                     syUserFootprint.setDeleted(0);
                                     footprintList.add(syUserFootprint);
                                 }
                             }
                         }
                     }
                }
            }
        }
        if(footprintList != null && footprintList.size() > 0){
            syUserFootprintMapper.insertFootprintList(footprintList);
        }
        if(footprintListBefore != null && footprintListBefore.size() > 0){
            syUserFootprintMapper.insertFootprintList(footprintListBefore);
        }
        long endTime = System.currentTimeMillis();
        log.info("***************************************结束执行足迹：executeCount=" + executeCount + "--endTime=" + endTime + "--耗时=" + (endTime - startTime));
    }

    public static void main(String[] args) {
        Date minByDate = DateUtils.updateMinByDate(new Date(), -1);
    }
}
